#!/usr/bin/python
# Author: Anirudh Sanjeev
"""
This file contains a class to implement a diagnostic to either execute a comand or read a file and retrieve the output and error code
"""
import commands, logging

logging.basicConfig
# ID of type of diagnostic, add more if required
TYPE_NONE = -1
TYPE_EXEC = 1000
TYPE_FILE = 1001

# Set up logging
logging.basicConfig()
log = logging.getLogger("diagnostic")
li = logging.info # Log info
ld = logging.debug # log debug

class Diagnostic:
    def __init__(self):
        """
        Initializing with init doesen't seem to be the best way for future proofing different kinds of tests. Each type of test will be"""
        type = TYPE_NONE
    def new_exec_diagnosis(self, command, title, description):
        li("New exec diagnosis")
        self.type = TYPE_EXEC

        self.description = description
        self.title = title
        self.command = command
        self.identifier = command

    def new_file_diagnosis(self, filename, title, description):
        li("New file diagnosis")
        self.type = TYPE_FILE

        self.filename = filename
        self.title = title
        self.description = description
        self.identifier = filename

    def go(self):
        """
        Executes the diagnostic
        """
        li("Now executing")

        self.result = "Diagnostic did not run"
        self.output = "None"
        self.success = False
        if self.type == TYPE_FILE:
            try:
                file_object = open(self.filename)
            except:
                # File can't be opened
                li("File can't be opened")
                self.result = "File could not be opened."
            try:
                output = file_object.read()
                self.output = output
                self.success = True
                self.result = "File was read properly"
            finally:
                file_object.close()
            li("File finished reading")

        elif self.type == TYPE_EXEC:
            import commands
            status = 255
            output = "no output"
            try:
                li("Trying to execute")
                statusoutput = commands.getstatusoutput(self.command)
                status = statusoutput[0]
                output = statusoutput[1]
            except:
                pass # I don't give a crap
            self.output = output
            if status == 0:
                self.result = "Diagnostic command seems to have run properly"
                self.success = True
            else:
                self.result = "Diagnostic command exited with an error code %d" % (status)
                self.success = False
            li("Execution seems to have finshed")
        else:
            # Nothing to execute
            raise NotDefinedError, "The diagnosis is not defined"
        li("Diagnostic routine finished")




# Unit tests for this module
if __name__ == "__main__":
    # TODO(anirudhs): replace simple output with unittests
    diagnostics = []
    whoami = Diagnostic()
    whoami.new_exec_diagnosis("whoami", "Who am I", "Returns username")
    diagnostics.append(whoami)

    xorg = Diagnostic()
    xorg.new_file_diagnosis("/etc/X11/xorg.conf", "XORG.conf", "the X.org configuration file. Contains all settings about your graphic, etc")
    diagnostics.append(xorg)


    for diagnostic in diagnostics:
        diagnostic.go()
        print "Name:", diagnostic.title
        print "Type:", diagnostic.type
        print "Description:", diagnostic.description
        print "Result:", diagnostic.result
        print "Success:", diagnostic.success
        print "Output:", diagnostic.output


